package com.hernie.piggymall.ware.listener;

import com.alibaba.fastjson.TypeReference;
import com.hernie.common.to.mq.OrderTo;
import com.hernie.common.to.mq.StockDetailTo;
import com.hernie.common.to.mq.StockLockedTo;
import com.hernie.common.utils.R;
import com.hernie.piggymall.ware.entity.WareOrderTaskDetailEntity;
import com.hernie.piggymall.ware.entity.WareOrderTaskEntity;
import com.hernie.piggymall.ware.service.WareSkuService;
import com.hernie.piggymall.ware.vo.OrderVo;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @Author HuangJp
 * @Date 2022/5/19
 * @Description
 */
@Slf4j
@Service
@RabbitListener(queues = "stock.release.stock.queue")
public class StockReleaseListener {

    @Autowired
    private WareSkuService wareSkuService;

    /**
     * 监听rabbitmq队列，解锁库存
     * 库存自动解锁
     *
     * 只要解锁库存的消息失败，一定要告诉服务解锁失败，启动手动ack机制
     * @param to
     * @param message
     */
    @RabbitHandler
    public void handleStockLockedRelease(StockLockedTo to, Message message, Channel channel) throws IOException {
        try {
            // message.getMessageProperties().getRedelivered(); 判断当前消息是否被第二次及以后（重新）派发过来的
//            Boolean redelivered = message.getMessageProperties().getRedelivered();
            wareSkuService.unlockStock(to);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); // 手动ack，告诉服务器消息已经处理成功后消息才会从队列中删除
        } catch (IOException e) {
            // 解锁失败 将消息重新放回队列，让别人消费
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }

    @RabbitHandler
    public void handleOrderCloseRelease(OrderTo orderTo, Message message, Channel channel) throws IOException {
        // 订单关闭，解锁库存
        try {
            wareSkuService.unlockStock(orderTo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); // 手动ack，告诉服务器消息已经处理成功后消息才会从队列中删除
        } catch (Exception e) {
            // 解锁失败 将消息重新放回队列，让别人消费
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }
}
